<?php
/* 
 * Copyright (c) 2018-2021   All rights reserved.
 * 
 * 创建时间：2021-10-02 15:56
 *
 * 项目：rm  -  $  - generateControllerHelper.php
 *
 * 作者：liwei 
 */

namespace modules\levmodules\helpers;

use Lev;
use lev\base\Modelv;
use lev\base\Modulesv;
use lev\helpers\dbHelper;
use lev\helpers\ModulesHelper;
use lev\helpers\SettingsHelper;
use lev\widgets\inputs\inputsWidget;
use modules\levmodules\helpers\generates\generateCtypeHelper;

!defined('INLEV') && exit('Access Denied LEV');


class generateControllerHelper extends generateHelper
{

    public static function replaceVars($iden, $replaceParam = [])
    {
        $replaceParam += parent::replaceVars($iden, $replaceParam); // TODO: Change the autogenerated stub
        return $replaceParam;
    }

    public static function createAdminController($iden, $adminNavs, $replaces = []) {
        if ($adminNavs) {
            foreach ($adminNavs as $v) {
                $route = explode("/", $v['link'])[0];
                if (empty($route)) {
                    static::$tips .= $v['id'] . $v['tableName'] . '<tips>路由不能为空且不能以"/"开头</tips> <br>';
                    continue;
                }
                if ($v['ctype'] >1) {
                    generateCtypeHelper::callCtype($v['ctype'], $iden, $v, $replaces, !$v['forceGen']);
                    continue;
                }
                if ($v['tableName']) {
                    $v['tableName'] = Modelv::preTableName($v['tableName']);
                    $tab = dbHelper::tableName($v['tableName'], false);
                    $formName = '_' . strtolower($tab);

                    $tabRoute = str_replace('_', '-', $tab);
                    $rt = Lev::ucfirstv($tabRoute);

                    $replaces['{#tabName}'] = $rt;
                    $replaces['{#tabRoute}'] = $tabRoute;
                    $replaces['{{adminNavName}}'] = $v['name'];
                    $replaces['{{$tableName}}'] = $v['tableName'];
                    $replaces['{{$addRoute}}'] = Modelv::formRoute($formName);
                    $replaces['pre_admin_user'] = $tab;
                    $replaces['userModelHelper'] = lcfirst($rt) . 'ModelHelper';
                    $replaces['BaseUserModel'] = 'Base' . ($rt) . 'Model';
                    $replaces['"{{allColumns}}"'] = static::varExportv($cols = dbHelper::getColumnsComment($v['tableName']));
                    $replaces['"{{inputs}}"'] = static::varExportvInputs($v['tableName']);
                    $replaces['{{srhTitle}}'] = '';
                    $replaces['{{srhkeyFiled}}'] = '';

                    $replaces['"{{showColumnsConfig}}"'] = static::getShowColumnsConfig($cols);
                    $replaces['"{{allColumnsType}}"'] = static::varExportv(dbHelper::getTableColumns($v['tableName']));

                    $replaces['admin-user'] = '';
                    $replaces['AdminUser'] = '';

                    static::generates($iden, $route, $replaces, !$v['forceGen'], $v['ctype']);
//                if ($v['formInputs']) {
//                    $formName = $v['formInputs'];
//                    generateFormHelper::generates($iden, $v['tableName'], $v['formInputs'], $formName, $replaces, !$v['forceGen']);
//                }
//                if ($v['formInputs'] != $tab) {
//                    generateFormHelper::generates($iden, $v['tableName'], $tab, $tab, $replaces, !$v['forceGen']);
//                }
                    generateFormHelper::generates($iden, $v['tableName'], $tab, $formName, $replaces, !$v['forceGen']);
                }
            }
            static::$tips && Lev::setNotices(static::$tips, true);
        }
    }
    public static function generates($iden, $route, $replaces = [], $forceGen = false, $ctype = 0) {
        $ckModule = static::isExistIden($idenDir = ModulesHelper::getIdenDir($iden));
        if (!$ckModule) {
            static::$tips .= '请先创建模块 ';
            return Lev::responseMsg(-10111, '请先创建模块');
        }
        $moduleIdenDir = Lev::$aliases['@modules'] . '/' . $idenDir;
        $className = Lev::ucfirstv($route);
        $ckController = $moduleIdenDir . '/controllers/_gen/Base' . $className . '.php';
        if (!$forceGen && is_file($ckController)) {
            static::$tips .= ' <tips>控制器已经创建过了！</tips>'.basename($ckController).'<br>';
            return Lev::responseMsg(-10111, '控制器已经创建过了！'.$ckController);
        }
        $generateDir = dirname(__DIR__) . '/_generates/_controllers/_levcc';
        $replaces = static::replaceVars($iden, $replaces);
        $replaces['AdminUser']       = $className;
        $replaces['admin-user']      = $route;
        $unFiles[$moduleIdenDir . '/controllers/'.$className.'Controller.php'] = 1;
        $unFiles[$moduleIdenDir . '/table/'.$replaces['pre_admin_user'].'/'.$replaces['userModelHelper'].'.php'] = 1;

        static::doGenerateFiles($generateDir, $moduleIdenDir, array_keys($replaces), array_values($replaces), $unFiles);
        static::$tips .= ' <span class="color-green">控制器文件创建成功：'.basename($ckController).'</span><br>';

        if (intval($ctype) === 1) {
            $replaces['ReceivePushController'] = 'ReceivePush'.$replaces['{#tabName}'].'Controller';
            $generateDir = dirname(__DIR__) . '/_generates/_controllers/_receive_push';
            $unFiles[$moduleIdenDir . '/controllers/ReceivePushController.php'] = 1;
            $unFiles[$moduleIdenDir . '/controllers/ReceivePush'.$replaces['{#tabName}'].'Controller.php'] = 1;
            static::doGenerateFiles($generateDir, $moduleIdenDir, array_keys($replaces), array_values($replaces), $unFiles);
            static::$tips .= ' <span class="color-green"><tips>数据推送</tips>控制器文件创建成功：ReceivePush'.$replaces['{#tabName}'].'Controller</span><br>';

            if (!Lev::actionOnce('updateSettings'.$iden) && is_file($file = __DIR__.'/../migrations/_receivePushSettings.php')) {
                $rows = include_once $file;
                static::updateSettings($iden, $rows);
            }
        }

        return Lev::responseMsg(1, '', ['files'=>static::$generateFiles]);
    }

    public static function updateSettings($iden, $rows) {
        if ($rows) {
            SettingsHelper::updateSettings($iden, $rows);
            ModulesHelper::addClassify($iden, 'receivePushSet', '推送设置');
            inputsWidget::setCaches();
            ModulesHelper::setCaches();
        }
    }

    public static function getShowColumnsConfig($columns)
    {
        foreach ($columns as $k => $v) $lens[] = strlen($k);
        $max = max($lens);

        $string = "array(\n";
        foreach ($columns as $k => $v) {
            $thattr = stripos($k, 'desc') !== false ? '' : 'wd30 nowrap';
            $len = $max - strlen($k);
            $nbsp = '';
            for ($i=0; $i<$len; $i++) $nbsp .= ' ';
            $del = in_array($k, ['settings', 'addtime']) ? '//' : '';
            $order = stripos($k, 'order') !== false ? 1 : 'null';
            $string .= "                $del'$k'$nbsp => array('order' => $order, 'name' => '$v', 'thattr' => '$thattr', 'merge' => []),\n\n";
        }
        $string .= '            )';
        return $string;
    }

    public static function varExportvInputs($tableName)
    {
        $TableColumns = dbHelper::getTableSchema($tableName);
        $string = "array(\n";
        foreach ($TableColumns as $v) {
            $title = $v['Comment'] ?: ucfirst($v['Field']);
            $inputname = $v['Field'];
            $inputtype = stripos($v['Type'], 'text') !== false ? 'textarea' : 'text';
            $placeholder = $inputname === 'settings' ? '<tips>【提示】序列化字段不了解情况下不要修改，否则会导致整个字段数据丢失</tips>' : '';
            $string .= "
            '{$inputname}' => array (
                    'moduleidentifier' => 'levcc',
                    'classify'         => '',
                    'title'            => '{$title}',
                    'placeholder'      => '{$placeholder}',
                    'inputname'        => '{$inputname}',
                    'inputtype'        => '{$inputtype}',
                    'inputvalue'       => '',
                    'settings'         => '',
                    'displayorder'     => '0',
                    'status'           => '0',
            ),";
        }
        $string .= "\n        )";
        return $string;
    }

}